<template>
    <div class="wrapper">

        <el-table ref="tableRef" :data="tableData" v-bind:border="true" style="width: 100%"
            v-bind:highlight-current-row="true" :max-height="tableHeight" row-key="id" :header-cell-style="{
                'background': '#1e78bf', 'color': '#FFFFFF', 'font-size': '16px',
                'font-weight': 'bold'
            }" @cell-dblclick="onUpdateUser">
            <template #empty>
                <span>无数据</span>
            </template>
            <el-table-column type="selection" width="55" v-bind:align="'center'" />
            <el-table-column v-bind:align="'center'" prop="name" label="姓名" width="180">
            </el-table-column>
            <el-table-column v-bind:align="'center'" prop="status" label="状态" width="180">
            </el-table-column>
            <el-table-column v-bind:align="'center'" prop="roleusers" label="角色" >
                <template #default="scope">
                    <el-tag v-for="roleuser in scope.row.roleusers" :key="roleuser.id">{{ roleuser.role.name }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column v-bind:align="'center'" prop="cfs_id" label="站点" width="180" :formatter="onFormatter"/>
            <el-table-column v-bind:align="'center'" prop="remark" label="备注" width="180"/>
        </el-table>

        <el-button-group class="bg">
            <el-button class="btn" type="primary"  @click="onAddUser">增加用户</el-button>
            <el-button class="btn" type="primary"  @click="onDeleteUser">删除用户</el-button>
            <el-button class="btn" type="primary"  @click="onResetPassword">重置密码</el-button>
            <!-- <el-button class="btn" type="primary" :icon="Notification" @click="onChooseRole">站点</el-button> -->
        </el-button-group>
        <div class="page">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[50, 100, 150, 200]"
                layout="sizes, prev, pager, next" :total="totalnum" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
      
    </div>
    <el-dialog v-model="dialogTableVisible" title="用户维护" draggable destroy-on-close>
        <User :data="paramUser" @yh-newuser="onYhnewuser($event)" @yh-updateuser="onYhupdateuser($event)"
            @yh-closedialog="onCloseDialog">
        </User>
    </el-dialog>
    <el-dialog v-model="dialogUserRoleVisible" title="用户角色维护" draggable destroy-on-close>
        <ChooseRole :data="paramUser" @yh-closedialog="onCloseDialog">
        </ChooseRole>
    </el-dialog>
    
</template>
<script setup lang='ts' name="SysUsers">
import { Request } from '@/app/request';

import type { UserModel } from '@/common/types/model';
// import { Delete, Notification, Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElTable } from 'element-plus';
import { findIndex, forEach, forEachRight, includes, isEmpty } from 'lodash';
import { ComputedRef, onMounted, ref } from 'vue';
import { useTableInfo } from '@/hooks/useTable';
import ChooseRole from './ChooseRole.vue';
import User from './User.vue';
import { tableMaxHeightAdjust } from '@/common/const';
import { useAppStore } from '@/store/app';
import { transFormatter } from '@/common/tools';

const tableData = ref<Array<UserModel>>([]);
const dialogTableVisible = ref(false);
// const dialogQueryVisible = ref(false);
const dialogUserRoleVisible = ref(false);
const tableHeight = ref(100);
let queryWhere = {};
let paramUser: UserModel | undefined;
const tableRef = ref<InstanceType<typeof ElTable>>()
const { cyCfs } = useAppStore();

const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'cfs_id') {
        data = cyCfs;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};


const onRefresh = async () => {

    const req = new Request('用户查询', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        ...queryWhere
    });
    const r = await req.post();

    totalnum.value = r.ext;

    tableData.value = [];
    if (!isEmpty(r.obj)) {
        forEach(r.obj, (value) => {
            tableData.value.push(value);
        })
    }
}
const { currentPage, orders, pageSize, totalnum, handleSizeChange, handleCurrentChange, handleSortChange } = useTableInfo(onRefresh);
onMounted(() => {
    onRefresh();
    tableHeight.value = window.innerHeight - Math.ceil(tableRef.value?.$el.getBoundingClientRect().bottom ) + tableMaxHeightAdjust;
});

const onAddUser = () => {
    paramUser = undefined;
    dialogTableVisible.value = true;
}
const onUpdateUser = (row: any, column: any, cell: any, event: any) => {
    paramUser = row;
    // console.log(paramUser);
    dialogTableVisible.value = true;
}
const onDeleteUser = async () => {
    const rows = tableRef.value?.getSelectionRows();
    const names = Array<string>();
    const ids = Array<number>();
    forEach(rows, (v: any) => {
        names.push(v.name);
        ids.push(v.id);
    });
    const msg = names.join(',     ');
    const delids = ids.join(',');
    const cr = await ElMessageBox.confirm(msg, '确认删除如下用户', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        return true;
    }).catch(() => {
        return false;
    });
    if (cr) {
        // 
        const req = new Request('用户删除', {ids})
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(tableData.value, (v: any, i: number) => {
                if (includes(ids, v.id)) {
                    tableData.value.splice(i, 1);
                }
            })
        }
    }

}
const onResetPassword = async () => {
    const rows = tableRef.value?.getSelectionRows();
    const names = Array<string>();
    const ids = Array<number>();
    forEach(rows, (v: any) => {
        names.push(v.name);
        ids.push(v.id);
    });
    const msg = names.join(',     ');
    const cr = await ElMessageBox.confirm(msg, '确认如下用户恢复初始密码', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        return true;
    }).catch(() => {
        return false;
    });
    if (cr) {
        const req = new Request('用户密码重置', {ids})
        await req.post();
    }
}

const onYhnewuser = (data: UserModel) => {
    tableData.value.push(data);
}
const onYhupdateuser = (data: UserModel) => {
    const i = findIndex(tableData.value, (o) => { return o.id === data.id });
    tableData.value[i] = data;
}
const onCloseDialog = async (arg: any) => {
    if (dialogTableVisible.value) {
        dialogTableVisible.value = false;
    }
   
    if (dialogUserRoleVisible.value) {
        onRefresh();
        dialogUserRoleVisible.value = false;
    }
}
const onChooseRole = () => {
    const rows: Array<UserModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length !== 1) {
        ElMessage.info('请选择一个用户');
        return;
    }
    // const user = rows[0];
    paramUser = rows[0]
    dialogUserRoleVisible.value = true;
}
const onQueryUser = () => {
    
    // dialogQueryVisible.value = true;
}

</script>
<style lang='scss' scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}
</style>